package com.xb.loan.cashier.alipay.web;

import com.opensymphony.xwork2.ActionSupport;
import com.xb.loan.cashier.alipay.util.CSVUtils;
import com.xb.loan.cashier.alipay.util.MD5;
import com.xb.loan.cashier.alipay.util.WebUtil;
import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@Controller
@Scope("prototype")
public class AccountAction extends ActionSupport {
	
	 @Value("${md5key}")
	 private String md5key;
	 
    public void query() throws Exception {
    	Map<String, String> params = WebUtil.getRequetParams( ServletActionContext.getRequest());
    	System.out.println("query params="+params.toString());
    	String pageNo = "1";
    	String pageSize = "5000";
    	String date = "2016-07-06 12:13:22";
    	String transCode = "6001";
    	if (params!=null && params.size()>0) {
    		pageNo = params.get("page_no");
    		pageSize = params.get("page_size");
    		date = params.get("gmt_start_time");
    		transCode = params.get("trans_code");
		}
    	String realpath = ServletActionContext.getServletContext().getRealPath("/accountFiles");
    	System.out.println("realpath>>>>>>>>>>"+realpath);
    	File file = new File(realpath);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        date = sdf2.format(sdf1.parse(date));
        List<List<String>> list = null;
        StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        for (File f: file.listFiles()) {
        	if (f.getName().contains(date+"_账务明细.csv")) {
        		list = CSVUtils.readCSVFile(f.getAbsolutePath());
				break;
			}
		}
        xml.append("<alipay>");
        xml.append("<is_success>T</is_success>");
        xml.append("<response>");
        xml.append("<account_page_query_result>");
        xml.append("<account_log_list>");
        for (int i = 0; i < list.size(); i++) {
			if (i>=5 && i<=list.size()-5) {
				List<String> csvList = list.get(i);
				String tradeType = csvList.get(10).toString().trim();
				if ("6001".equals(transCode)) {
					if (!"支付".equals(tradeType)) {//非充值
						continue;
					}
				} else if ("5004".equals(transCode)){
					if (!"批量付款到银行账户".equals(tradeType)) {//非提现
						continue;
					}
				}
				xml.append("<AccountQueryAccountLogVO>");
				xml.append("<trans_out_order_no>"+csvList.get(1).trim()+"</trans_out_order_no>");
				xml.append("<merchant_out_order_no>"+csvList.get(2).trim()+"</merchant_out_order_no>");
				xml.append("<trans_date>"+csvList.get(4).trim()+"</trans_date>");
				xml.append("<buyer_account>"+csvList.get(5).trim()+"</buyer_account>");
				xml.append("<total_fee>"+csvList.get(6).trim()+"</total_fee>");
				xml.append("<outcome>"+csvList.get(7).trim().replace("-", "")+"</outcome>");
				xml.append("<bank_account_no>123456789012</bank_account_no>");
				xml.append("</AccountQueryAccountLogVO>");
			}
		}
        xml.append("</account_log_list>");
        xml.append("<has_next_page>F</has_next_page>");
        xml.append("<page_no>"+(pageNo==null?"":pageNo)+"</page_no>");
        xml.append("<page_size>"+(pageSize==null?"":pageSize)+"</page_size>");
        xml.append("</account_page_query_result>");
        xml.append("</response>");
        xml.append("<sign>${sign}</sign>");
        xml.append("<sign_type>MD5</sign_type>");
        xml.append("</alipay>");
        String msg = xml.toString();
        msg = msg.replace("${sign}", sign(msg, md5key, "UTF-8"));
        System.out.println(msg);
        PrintWriter out = null;
        String contentType = "text/html;charset=utf-8";
        ServletActionContext.getResponse().setContentType(contentType);
        out = ServletActionContext.getResponse().getWriter();
        out.print(msg);
        out.flush();
        out.close();
    }
    
    public String sign(String data, String signKey, String charset){
    	String result = null;
        try {
            Document document = DocumentHelper.parseText(data);
            Element wrapper = (Element) document.getRootElement().selectSingleNode(
            "/alipay/response/account_page_query_result");
            String hasNextPage = wrapper.elementText("has_next_page");
            String pageNo = wrapper.elementText("page_no");
            String pageSize = wrapper.elementText("page_size");
            Element accountLogList = wrapper.element("account_log_list");
            OutputFormat format = new OutputFormat();
            format.setExpandEmptyElements(true); //一定要设置
            StringWriter accountLogListContent = new StringWriter();
            XMLWriter writer = new XMLWriter(accountLogListContent, format);
            writer.write(accountLogList);
            String payload = String.format(
            "account_log_list=%s&has_next_page=%s&page_no=%s&page_size=%s",
            accountLogListContent, hasNextPage, pageNo, pageSize);
            result = MD5.sign(payload, signKey, charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
		return result;
    }
    
    public static void main(String[] args) throws Exception {
		new AccountAction().query();
	}

}
